package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码格式为utf8
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        // 1.从请求中获取到用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 2.判断用户名或密码是否正确
        if (username == null || username.equals("") || password == null || password.equals("")) {
            // 用户名密码残缺, 登录必然失败!!
            String html = "<h3>账号或密码错误1</h3>";
            resp.getWriter().write(html);
            return;
        }

        // 3.从数据库中读取，用户名和密码，并判断是否存在
        UserDao userDao = new UserDao();
        // 下列的username就是1.中获取的
        User user = userDao.selectByUsername(username);
        if(user == null) {
            String html = "<h3>账号或密码错误2</h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())) {
            String html = "<h3>账号或密码错误3</h3>";
            resp.getWriter().write(html);
            return;
        }

        // 4. 用户名和密码正确，创建一个会话
        HttpSession session = req.getSession(true);
        // 将用户存入session中，用户在后期访问其他网站时，就能通过session访问到之前的user对象
        session.setAttribute("user",user);

        // 5.重定向，跳转至主页
        resp.sendRedirect("blog_list.html" );

    }

    //重写doGet方法，用来判断登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession(false);

        // session不存在则设置为403
        if(session == null) {
            resp.setStatus(403);
            return;
        }

        User user = (User) session.getAttribute("user");
        // session存在，但用户处于未登录的状态
        if(user == null) {
            resp.setStatus(403);
            return;
        }

        //session存在设置为200
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        user.setPassword(""); // 把密码设置为空，保密
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
